package com.quick.framework.security.handle;


import com.alibaba.fastjson2.JSON;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.core.domain.LoginUser;
import com.quick.common.utils.ServletUtils;
import com.quick.framework.event.LogoutEvent;
import com.quick.framework.manager.AsyncManager;
import com.quick.framework.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义退出处理类 返回成功
 *
 * @Author: Administrator
 * @Date: 2023/7/27
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ApplicationContext applicationContext;


    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser))
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            applicationContext.publishEvent(new LogoutEvent(this,userName));
        }
        ServletUtils.renderString(response, JSON.toJSONString(ApiResponse.success("退出成功")));
    }
}
